package com.wsc.crawler.DNS;

import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Date;

import org.apache.log4j.Logger;
import org.xbill.DNS.Address;

import com.wsc.crawler.URLutils.URLBean;
import com.wsc.crawler.grabber.URLBeanQueue;

public class DNSClient {
	public URLBeanQueue queue ;
//	public static URLQueue dnsqueue = new URLQueue();
	public ArrayList<URLBean> resolvedhostlist=new ArrayList<URLBean>();
	Logger log=Logger.getLogger(DNSClient.class.getName());
	public ArrayList<URLBean> UnresolvedHosts= new ArrayList<URLBean>();
	public InetAddress addr ;
	
	public ArrayList<URLBean> ResolveHosts(URLBeanQueue queue) throws MalformedURLException, UnknownHostException {
	
		this.queue=queue;


		long startTime = (new Date()).getTime();
		while (queue.size() != 0) {
			URLBean urlbean=new URLBean();
			URL url = queue.dequeue().getOriginalURL();
		
			//set unresolved host in URLBean
			urlbean.setOriginalURL(url);
			System.out.println("Resolving :"+url.toString());
			try{
				addr = Address.getByName(url.getHost());
			// if no exception execute following statements 
				log.info(queue.size()+" Replaced IP: "+url.toString().replaceFirst(url.getHost(), addr.getHostAddress()));
				URL l=new URL(url.toString().replaceFirst(url.getHost(), addr.getHostAddress()));
				//set dns resolved url in URLBean
				urlbean.setDnsresolvedHost(l);
				resolvedhostlist.add(urlbean);
			}catch(Exception e){
				//set the error message in URLBean
				urlbean.setMessage(e.getMessage());
				UnresolvedHosts.add(urlbean);
			}
	 
 		}

		long endTime = (new Date()).getTime();
		log.info("Time taken to Resolve "+resolvedhostlist.size()+" Hosts is : "+ (endTime - startTime)+"ms");

		return resolvedhostlist;

	}
 
	// call this method explicitly to get unresolved hosts. 
public ArrayList<URLBean> getUnresolvedHosts(){
	return this.UnresolvedHosts;
}
}
